package com.hetongxue.utils;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;

/**
 * @Description: 邮件工具类
 * @ClassNmae: MailUtils
 * @Author: 何同学
 * @DateTime: 2022-03-21 23:11
 **/
@Component
public class MailUtil {

    @Value("${spring.mail.username}")
    private String from;

    @Resource
    private JavaMailSender javaMailSender;

    /**
     * @Description: 发送简单邮件
     * @Author: 何同学
     * @DateTime: 2022/2/24 23:29
     **/
    public String sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        // 设置发送方邮箱
        message.setFrom(this.from);
        // 设置接收方邮箱
        message.setTo(to);
        // 设置发送主题
        message.setSubject(subject);
        // 设置发送内容(文本)
        message.setText(content);
        // 发送
        javaMailSender.send(message);
        return "发送成功";
    }

    /**
     * @Description: 发送带附件的邮件
     * @Author: 何同学
     * @DateTime: 2022/2/26 15:15
     **/
    public String sendAttachmentMail(String to, String subject, String content, MultipartFile attachment) {
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            // 设置发送方邮箱
            mimeMessageHelper.setFrom(this.from);
            // 设置接收方邮箱
            mimeMessageHelper.setTo(to);
            // 设置发送主题
            mimeMessageHelper.setSubject(subject);
            // 设置发送内容(文本)
            mimeMessageHelper.setText(content);
            // 设置附件信息
            String fileName = attachment.getName() + "." + FilenameUtils.getExtension(attachment.getOriginalFilename());
            mimeMessageHelper.addAttachment(fileName, new ByteArrayResource(attachment.getBytes()));
            // 发送
            javaMailSender.send(mimeMessage);
            return "发送成功";
        } catch (MessagingException e) {
            e.printStackTrace();
            return "消息异常";
        } catch (IOException e) {
            e.printStackTrace();
            return "文件异常";
        }
    }

}
